package com.spark.lola.hander;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.spark.lola.feign.PurReportFeignService;
import com.spark.lola.request.CompanyStatisticsRequest;
import com.spark.lola.statistics.entity.StatisticsDestination;
import com.spark.lola.statistics.vo.PurchaseStatisticsVo;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.DatesUtil;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.common.util.TimeUtil;
import com.spark.lola.support.core.constant.TimeConstant;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.mybatis.entity.QueryParam;
import com.spark.lola.support.netty.annotation.HawkBean;
import com.spark.lola.support.netty.annotation.HawkMethod;
import com.spark.lola.support.netty.api.NettyPermissionService;
import com.spark.lola.support.netty.constant.NettyCommands;
import com.spark.lola.support.wms.cache.CollectionCache;
import com.spark.lola.support.wms.constant.WmsNettyCommands;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 采购大屏 socket服务
 * @Author: DengYeJun
 * @Date: 2020/6/12 15:27
 */
@HawkBean
public class PurchaseHandler {
    private static final Logger logger = LoggerFactory.getLogger(PurchaseHandler.class);
    @Autowired
    NettyPermissionService nettyPermissionService;
    @Autowired
    private PurReportFeignService purReportFeignService;
    /**
     * 查询采购概况
     */
    @HawkMethod(cmd = WmsNettyCommands.QUERY_PURCHASE_STATISTICS,version = NettyCommands.COMMANDS_VERSION)
    public String querystatistics(long seqId, byte[] body, ChannelHandlerContext ctx) {
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        // 获取时间类型
        String json = new String(body);
        JSONObject request = JSON.parseObject(json);
        String timeType = request.getString("timeType");
        String channelId = ctx.channel().id().asLongText();
        // 获取用户ID
        String userId = nettyPermissionService.getUserId(channelId);
        logger.info("管理员【{}】通道【{}】参数【{}】请求采购概况", userId, channelId,timeType);
        // 获取管理员
        ShiroUser shiroUser = CollectionCache.employees.get(Long.valueOf(userId));
        // 根据时间类型
        String[] times = parseTime(timeType);
        PurchaseStatisticsVo vo = purReportFeignService.employeeStatistics(shiroUser,times[0],times[1]);
        return JSON.toJSONString(ResponseBean.success(vo));
    }

    /**
     * 查询纸厂概况
     */
    @HawkMethod(cmd = WmsNettyCommands.QUERY_COMPANY_STATISTICS,version = NettyCommands.COMMANDS_VERSION)
    public String queryCompanystatistics(long seqId, byte[] body, ChannelHandlerContext ctx) {
        InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        // 获取时间类型
        String json = new String(body);
        CompanyStatisticsRequest request = JSON.parseObject(json,CompanyStatisticsRequest.class);
        String channelId = ctx.channel().id().asLongText();
        // 获取用户ID
        String userId = nettyPermissionService.getUserId(channelId);
        logger.info("管理员【{}】通道【{}】参数【{}】请求纸厂统计", userId, channelId,request.getTimeType());

        QueryParam<StatisticsDestination> queryBean =new QueryParam<>();
        queryBean.setSortFields("orderPayment_d");
        queryBean.setPageIndex(1);
        queryBean.setPageSize(request.getSize());
        queryBean.setQueryList(bindParams(request.getTimeType()));
        Page<StatisticsDestination> page=null;

        switch (request.getTimeType()) {
            case TimeConstant.TODAY:
                page = purReportFeignService.dayDestinationReport(queryBean,0L);
                break;
            case TimeConstant.WEEK:
                page = purReportFeignService.sumDestinationReport(queryBean);
                break;
            case TimeConstant.MONTH:
                page = purReportFeignService.monthDestinationReport(queryBean,0L);
                break;
            default:
                break;
        }
        if(page==null){
            return JSON.toJSONString(ResponseBean.error("参数不正确!"));
        }
        return JSON.toJSONString(ResponseBean.success(page));
    }

    private static List<QueryCondition> bindParams(String timeType){
        String[] times = parseTime(timeType);
        List<QueryCondition> query =new ArrayList<>();
        switch (timeType){
            case TimeConstant.TODAY: {
                QueryCondition queryCondition = new QueryCondition();
                queryCondition.setKey("createDate");
                queryCondition.setOper("=");
                queryCondition.setValue(TimeUtil.getCurrentDate());
                query.add(queryCondition);
                break;
            }
            case TimeConstant.WEEK: {
                QueryCondition start = new QueryCondition();
                start.setKey("createDate");
                start.setOper(">=");
                start.setValue(times[0]);
                QueryCondition end = new QueryCondition();
                end.setKey("createDate");
                end.setOper("<=");
                end.setValue(times[1]);
                query.add(start);
                query.add(end);
                break;
            }
            case TimeConstant.MONTH: {
                QueryCondition queryCondition = new QueryCondition();
                queryCondition.setKey("createMonth");
                queryCondition.setOper("=");
                queryCondition.setValue(TimeUtil.getMonth(new Date()));
                query.add(queryCondition);
                break;
            }
            default:
                break;
        }
        return query;
    }

    private static String[] parseTime(String timeType){
        String[] times = new String[2];
        Date now = new Date();
        switch (timeType) {
            case TimeConstant.TODAY:
                times[0] = TimeUtil.getStartOfDay(now);
                times[1] = TimeUtil.getEndOfDay(now);
                break;
            case TimeConstant.YESTERDAY:
                break;
            case TimeConstant.WEEK:
                times[0] = TimeUtil.getTime(DatesUtil.getBeginDayOfWeek());
                times[1] = TimeUtil.getTime(DatesUtil.getEndDayOfWeek());
                break;
            case TimeConstant.MONTH:
                times[0] = TimeUtil.getTime(DatesUtil.getBeginDayOfMonth());
                times[1] = TimeUtil.getTime(DatesUtil.getEndDayOfMonth());
                break;
            case TimeConstant.YEAR:
                times[0] = TimeUtil.getTime(DatesUtil.getBeginDayOfYear());
                times[1] = TimeUtil.getTime(DatesUtil.getEndDayOfYear());
                break;
            default:
                break;
        }
        return times;
    }


    public static void main(String[] args){
//        String[] times = parseTime(TimeConstant.YEAR);
//        for (String time : times) {
//            System.out.println((new SimpleDateFormat("yyyy-MM-dd 00:00:00")).format(new Date()));
//        }
        System.out.println(JSON.toJSONString(bindParams(TimeConstant.MONTH)));
    }
}
